/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.auth.ui

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.climber.android.auth.R
import com.climber.android.auth.api.AuthService
import com.climber.android.auth.api.RegisterRequestInfo
import com.climber.android.commonres.app.service.CoreService
import com.climber.android.commonres.app.service.OTPRequestInfo
import com.climber.android.commonres.helper.RxCountDown
import com.climber.android.commonres.helper.onClick
import com.climber.android.commonres.helper.showCountryCodeSpinner
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.util.UIHelper
import com.climber.android.commonsdk.api.APIError
import com.climber.android.commonsdk.api.ApiObserver
import com.climber.android.commonsdk.api.GlobalErrorProcessor
import com.climber.android.commonsdk.api.entity.APIResponse
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonsdk.app.AppEnv
import com.climber.android.commonsdk.arouter.ARouterPathConstants
import com.climber.android.commonsdk.util.APIDataHelper
import com.climber.android.commonsdk.util.WebLinkClickSpan
import io.ganguo.library.mvp.http.RxSchedulers
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.*
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.auth_activity_signup.*

/**
 * Created by Mikes at 2019-11-04 15:14
 */
@Route(path = ARouterPathConstants.PATH_SIGN_UP)
class AuthSignUpActivity : BaseMVPActivity<IPresenter>() {
    private var choosedCountryCode = AppConstants.DEFAULT_COUNTRY_CODE

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = R.layout.auth_activity_signup

    override fun initView() {
        tv_register_privacy.movementMethod = LinkMovementMethod.getInstance()
        tv_register_privacy.text = SpanUtils()
                .append("我已阅读并同意")
                .setForegroundColor(UIUtils.getColor(R.color.common_text_secondary_light))
                .append("《服务协议》")
                .setForegroundColor(UIUtils.getColor(R.color.common_green))
                .setClickSpan(WebLinkClickSpan(AppEnv.USER_AGREEMENT_URL, preferTitle = "服务协议"))
                .append("和")
                .setForegroundColor(UIUtils.getColor(R.color.common_text_primary))
                .append("《隐私政策》")
                .setForegroundColor(UIUtils.getColor(R.color.common_green))
                .setClickSpan(WebLinkClickSpan(AppEnv.PRIVACY_AGREEMENT_URL, preferTitle = "隐私政策"))
                .create()
    }

    override fun initListener() {
        getSmartToolBar()?.setRightViewClickListener(View.OnClickListener {
            setResult(Activity.RESULT_CANCELED)
            finish()
        })

        cbRegisterPrivacy.setOnCheckedChangeListener { _, isChecked ->
            tv_register_now.isEnabled = isChecked
        }

        tv_register_now.onClick {
            doRegister()
        }

        inputPhoneNumberView.registerLeftViewClick {
            inputPhoneNumberView.getLeftTextView().showCountryCodeSpinner(supportFragmentManager) {countryCode ->
                if(countryCode != null) choosedCountryCode = countryCode
            }
        }

        inputPhoneNumberView.registerSendSMSCodeClick {
            doSendSmsCode()
        }
    }

    override fun initData() {
    }

    private fun doSendSmsCode() {
        val phoneNumber = inputPhoneNumberView.getInputContent()
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastHelper.toastMessage(R.string.phone_number_empty)
            return
        }

        val otpRequestInfo = OTPRequestInfo.Register(countryCode = choosedCountryCode, number = phoneNumber)
        CoreService.coreServiceAPI
                .issueSendOTP(APIDataHelper.generateRequestBody(otpRequestInfo.apiParameters()))
                .compose(RxSchedulers.networkRequest<APIResponse>())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe {
                    UIHelper.showLoading(this)
                }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<APIResponse>() {
                    override fun success(apiResponse: APIResponse) {
                        UIHelper.hideLoading()

                        ToastHelper.toastMessage(R.string.sms_code_has_sent_to_mobile)

                        RxCountDown.startSMSCodeCountDown(this@AuthSignUpActivity, inputPhoneNumberView.getSendSMSCodeView())
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()
                    }
                })
    }

    /**
     * 此处注册成功后，返回登录页，要求用户登录一次。
     */
    private fun doRegister() {
        val nickName = nicknameView.getInputContent()
        val phoneNumber = inputPhoneNumberView.getInputContent()
        val smsCode = SMSCodeView.getInputContent()
        val password = passwordView.getInputContent()
        val passwordAgain = passwordAgainView.getInputContent()

        if(TextUtils.isEmpty(nickName)){
            ToastHelper.toastMessage(R.string.nickname_empty)
            return
        }

        if (TextUtils.isEmpty(phoneNumber)) {
            ToastHelper.toastMessage(R.string.phone_number_empty)
            return
        }

        if (TextUtils.isEmpty(smsCode)) {
            ToastHelper.toastMessage(R.string.please_input_otp)
            return
        }

        if(TextUtils.isEmpty(password) || TextUtils.isEmpty(passwordAgain)){
            ToastHelper.toastMessage(R.string.input_password)
            return
        }

        if(!StringUtils.equals(password, passwordAgain)){
            ToastHelper.toastMessage(R.string.password_should_match)
            return
        }

        val registerRequestInfo = RegisterRequestInfo.Mobile(nickName = nickName, countryCode = choosedCountryCode, number = phoneNumber, password = password, mobileOTP = smsCode)

        AuthService.authServiceAPI
                .register(APIDataHelper.generateRequestBody(registerRequestInfo.apiParameters()))
//                .flatMap { registerApiResponse ->
//                    if (registerApiResponse.isSuccessful()) {
//                        val loginRequestInfo = registerRequestInfo.loginRequestInfo()
//                        AuthService.authServiceAPI
//                                .issueGetLoginToken(APIDataHelper.generateRequestBody(loginRequestInfo.apiParameters()))
//                                .flatMap { rawResponse ->
//                                    TokenResponseTransfer().apply(rawResponse)
//                                }
//                                .flatMap { tokenResponse ->
//                                    if (tokenResponse.isSuccessful()) {
//
//                                        AuthService.getUserCardInfoAndWalletInfo()
//                                                .map { incUserInfo ->
//                                                    incUserInfo.hxUserInfo = HxUserInfo(hx_user = tokenResponse.data?.hx_user,
//                                                            hx_pwd = tokenResponse.data?.hx_pwd)
//                                                    incUserInfo.user_id = tokenResponse.data?.user_id
//
//                                                    incUserInfo
//                                                }
//                                    } else {
//                                        Observable.error(APIError.ServerError(errorCode = tokenResponse.getServerErrorCode(), errorMsg = tokenResponse.getServerErrorMsg()))
//                                    }
//                                }
//                    } else {
//                        Observable.error(APIError.ServerError(errorCode = registerApiResponse.getServerErrorCode(), errorMsg = registerApiResponse.getServerErrorMsg()))
//                    }
//                }
                .compose(RxSchedulers.networkRequest())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe { UIHelper.showLoading(this, null) }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<APIResponse>() {
                    override fun success(apiResponse: APIResponse) {
                        ToastHelper.toastMessage("您已注册成功，请登录。")
                        // 返回登录页，要求用户输入一次密码进行登录
                        setResult(Activity.RESULT_OK, Intent().putExtra("result", phoneNumber))
                        this@AuthSignUpActivity.finish()
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()
                    }
                })
    }
}